<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>MES总装扫码</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 15px;
            background-color: #fff;
            min-height: 100vh;
        }
        
        header {
            text-align: center;
            padding: 15px 0;
            border-bottom: 1px solid #e0e0e0;
            margin-bottom: 15px;
        }
        
        h1 {
            font-size: 18px;
            color: #333;
            font-weight: 600;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #666;
        }
        
        .scan-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
            width: 100%;
        }
        
        .scan-button {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background-color: #f0f0f0;
            color: #333;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .scan-button.active {
            background-color: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }
        
        .input-group {
            display: flex;
            margin-bottom: 20px;
        }
        
        .input-group input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            font-size: 16px;
        }
        
        .input-group button {
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-left: none;
            border-radius: 0 4px 4px 0;
            background-color: #f0f0f0;
            cursor: pointer;
            display: none;
        }
        
        .result-section {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .result-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .result-item:last-child {
            border-bottom: none;
        }
        
        .result-label {
            color: #666;
            font-size: 14px;
        }
        
        .result-value {
            color: #333;
            font-size: 14px;
            font-weight: 500;
            text-align: right;
        }
        
        .status-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            padding: 15px;
            text-align: center;
            background-color: #fff;
            border-top: 1px solid #eee;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
        }
        
        .status-success { color: #4caf50; }
        .status-error { color: #f44336; }
        .status-info { color: #2196f3; }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            display: none;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #1a73e8;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>MES总装扫码</h1>
        </header>
        
        <div class="form-group">
            <label>工位</label>
            <div class="scan-buttons">
                <button class="scan-button" id="btn-in" onclick="setScanType('IN')">上线扫码</button>
                <button class="scan-button active" id="btn-out" onclick="setScanType('OUT')">下线扫码</button>
            </div>
        </div>
        
        <div class="input-group">
            <input type="text" id="barcode-input" placeholder="请扫描整机SN码/或关键件码" autofocus>
        </div>
        
        <div id="result-section" class="result-section">
            <div class="result-item">
                <span class="result-label">扫码时间</span>
                <span id="scan-time" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span class="result-label">整机Lot_No</span>
                <span id="sn-code" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span class="result-label">产线信息</span>
                <span id="line-info" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span class="result-label">整机料号</span>
                <span id="part-code" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span class="result-label">整机名称</span>
                <span id="part-name" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span class="result-label">生产工单</span>
                <span id="wo-no" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span class="result-label">工单计划数</span>
                <span id="plan-qty" class="result-value">--</span>
            </div>
            <div class="result-item">
                <span id="scan-type-label" class="result-label">累计下线数量</span>
                <span id="accumulated-qty" class="result-value">--</span>
            </div>
        </div>
    </div>
    
    <div id="status-bar" class="status-bar status-info">
        请输入条码后按回车键
    </div>
    
    <div id="loading-overlay" class="loading-overlay">
        <div class="loading-spinner"></div>
    </div>
    
    <script>
        // 全局变量
        let currentScanType = 'OUT'; // 默认下线扫码
        
        // DOM元素
        const barcodeInput = document.getElementById('barcode-input');
        const statusBar = document.getElementById('status-bar');
        const loadingOverlay = document.getElementById('loading-overlay');
        const resultSection = document.getElementById('result-section');
        
        // 获取工单统计数据
        function fetchWorkOrderStats(barcode) {
            fetch(`/api/scan/workOrderStats?barcode=${encodeURIComponent(barcode)}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.ok ? response.json() : {})
            .then(data => {
                document.getElementById('plan-qty').textContent = data.planQty || '--';
                document.getElementById('accumulated-qty').textContent = currentScanType === 'IN' ? (data.onlineQty || '--') : (data.offlineQty || '--');
            })
            .catch(() => {
                document.getElementById('plan-qty').textContent = '--';
                document.getElementById('accumulated-qty').textContent = '--';
            });
        }
        
        // 设置扫码类型
        function setScanType(scanType) {
            currentScanType = scanType;
            
            // 更新按钮状态
            document.getElementById('btn-in').classList.remove('active');
            document.getElementById('btn-out').classList.remove('active');
            document.getElementById(scanType === 'IN' ? 'btn-in' : 'btn-out').classList.add('active');
            
            // 更新标签
            document.getElementById('scan-type-label').textContent = scanType === 'IN' ? '累计上线数量' : '累计下线数量';
            updateStatus(`当前模式：${scanType === 'IN' ? '上线扫码' : '下线扫码'}`, 'info');
        }
        
        // 处理条码输入
        barcodeInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const barcode = this.value.trim();
                if (barcode) {
                    processBarcode(barcode);
                    this.value = '';
                } else {
                    updateStatus('请输入有效条码', 'error');
                }
            }
        });
        
        // 音频播报
        function playSound(type) {
            // 音频文件路径
            const soundFiles = {
                success: '/video/success.mp3',
                repeat: '/video/repeat.mp3',
                no: '/video/no.mp3'
            };
            
            // 创建音频对象并播放
            const audio = new Audio(soundFiles[type]);
            audio.play().catch(error => {
                console.log('音频播放失败:', error);
            });
        }
        
        // 处理条码数据
        function processBarcode(barcode) {
            showLoading(true);
            updateStatus('正在处理扫码结果...', 'info');
            
            // 调用后端API
            fetch(`/api/scan/process?barcode=${encodeURIComponent(barcode)}&scanType=${encodeURIComponent(currentScanType)}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            })
            .then(response => response.json())
            .then(data => {
                showLoading(false);
                
                // 更新结果显示
                if (data.serialNo || data.lotNo || data.partCode || data.woNo) {
                    updateResultDisplay(data);
                }
                
                if (data.success) {
                    updateStatus(`扫码成功 - ${currentScanType === 'IN' ? '上线' : '下线'}`, 'success');
                    playSound('success');
                    // 扫码成功后获取最新的统计数据
                    fetchWorkOrderStats(barcode);
                } else {
                    updateStatus(data.errorMsg || '处理失败', 'error');
                    const soundType = data.errorMsg?.includes('重复') ? 'repeat' : 'no';
                    playSound(soundType);
                    // 即使失败也尝试获取统计数据（可能是重复扫码的情况）
                    fetchWorkOrderStats(barcode);
                }
                
                barcodeInput.focus();
            })
            .catch(error => {
                showLoading(false);
                updateStatus('网络错误，请重试', 'error');
            });
        }
        
        // 更新结果显示
        function updateResultDisplay(data) {
            // 更新扫码时间
            document.getElementById('scan-time').textContent = new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
            
            document.getElementById('sn-code').textContent = data.serialNo || data.lotNo || '--';
            document.getElementById('part-code').textContent = data.partCode || '--';
            document.getElementById('part-name').textContent = data.materialName || data.partName || '--';
            document.getElementById('wo-no').textContent = data.woNo || '--';
            
            // 更新产线信息
            const lineInfoElement = document.getElementById('line-info');
            if (data.Line_Code && data.Line_name) {
                lineInfoElement.textContent = `${data.Line_Code} ${data.Line_name}`;
            } else if (data.lineCode && data.lineName) {
                lineInfoElement.textContent = `${data.lineCode} ${data.lineName}`;
            } else if (data.eqptId && data.eqptDesc) {
                lineInfoElement.textContent = `${data.eqptId} ${data.eqptDesc}`;
            } else {
                lineInfoElement.textContent = '--';
            }
        }
        
        // 更新状态显示
        function updateStatus(message, type = 'info') {
            statusBar.textContent = message;
            statusBar.className = 'status-bar';
            statusBar.classList.add(type === 'success' ? 'status-success' : type === 'error' ? 'status-error' : 'status-info');
        }
        
        // 显示/隐藏加载动画
        function showLoading(show) {
            loadingOverlay.style.display = show ? 'flex' : 'none';
        }
        
        // 确保焦点始终在输入框
        function ensureFocus() {
            setTimeout(() => {
                if (document.activeElement !== barcodeInput) {
                    barcodeInput.focus();
                }
            }, 100);
        }
        
        // 处理外部扫描事件（PDA设备）
        function OnReceivedScanData(scanData) {
            if (scanData && scanData.trim()) {
                processBarcode(scanData.trim());
                return true; // 告诉设备已成功处理
            }
            return false;
        }
        
        // 尝试在全局对象上注册扫描事件处理函数
        window.OnReceivedScanData = OnReceivedScanData;
        
        // 如果是在特定PDA容器内运行，可能需要在document对象上也注册
        document.OnReceivedScanData = OnReceivedScanData;
        
        // 页面加载完成
        window.onload = function() {
            barcodeInput.focus();
            
            // 尝试检测PDA设备环境
            try {
                if (window.external && typeof window.external.OnReceivedScanData === 'function') {
                    // 有些PDA设备需要特殊的注册方式
                    console.log('检测到支持扫描的PDA设备');
                    updateStatus('已连接扫描设备，可直接扫描', 'success');
                }
            } catch (e) {
                // 忽略不支持的设备错误
                console.log('标准浏览器环境，等待键盘输入');
            }
        };
        
        // 添加焦点管理
        document.querySelectorAll('button').forEach(button => {
            button.addEventListener('click', ensureFocus);
        });
        
        document.addEventListener('click', function(event) {
            if (event.target !== barcodeInput && !barcodeInput.contains(event.target)) {
                ensureFocus();
            }
        });
        
        barcodeInput.addEventListener('blur', ensureFocus);
    </script>
</body>
</html>